package common.controls.item
{
	import cn.flashk.controls.Image;
	
	import common.controls.AKSprite;
	import common.controls.item.attribute.ItemAttribute;
	import common.controls.item.events.ItemAttributeEvent;
	
	import config.Path;
	
	import flash.text.TextField;
	
	
	[Event(name="itemShapeChange", type="common.events.ItemEvent")]
	/**  
	 * 
	 * @author carrey
	 * */ 
	public class Item extends AKSprite
	{
		protected var _parentContainer:ItemContainer;
		protected var _attribute:ItemAttribute;
		private var _txt:TextField;
		
		private var _image:Image;
		
		public function Item( att:ItemAttribute=null )
		{
			super();
			_attribute = att;
			init();
		}
		
		protected function init():void
		{
			if( _attribute==null )
			{
				createItemAttribute();
			}
			_image = new Image();
			_image.source = Path.getItemResPath(_attribute.itemId);
//			_image.backgroundAlpha = 0;
//			_image.addEventListener( ResLoaderEvent.COMPLETE, onImageLoaded, false, 0, true );
			
			addChild( _image );
		}
		
		public function destroy():void
		{
			_attribute = null;
			
			if( _image != null )
			{
//				_image.removeEventListener( ResLoaderEvent.COMPLETE, onImageLoaded );
				_image.destroy();
				_image = null;
			}
			_parentContainer = null;
			if(_txt!=null&&_attribute!=null)
			{
				_attribute.removeEventListener(ItemAttributeEvent.CHANGED_STACK,onStack);
			}
			_txt = null;
		}
		
		public function get attribute():ItemAttribute
		{
			return _attribute;
		}
		
		override public function setSize(w:int, h:int):void
		{
			super.setSize( w, h );
			
			if( _image != null )
			{
				_image.setSize( w, h );
				setTxt(w, h);
			}
		}
		private function setTxt(w:int, h:int):void
		{
			if(_txt==null&&_attribute!=null)
			{
				_txt = new TextField();
				_txt.width = w;
				_txt.height = 17;
				_txt.mouseEnabled = false;
				if(_attribute.stack>1)
				{
					_txt.text = _attribute.stack.toString();
				}else{
					_txt.text = "";
				}
				_txt.width = _txt.textWidth+5;
				addChild( _txt );
				_attribute.addEventListener(ItemAttributeEvent.CHANGED_STACK,onStack);
			}
			_txt.y = h-_txt.height;
			_txt.x = w-_txt.width;
		}
		private function onStack(evt:ItemAttributeEvent):void
		{
			if(_attribute.stack>1)
			{
				_txt.text = _attribute.stack.toString();
			}else{
				_txt.text = "";
			}
		}
		
		internal function setParentContainer( value:ItemContainer ):void
		{
			_parentContainer = value;
		}
		
		public function get parentContainer():ItemContainer
		{
			return _parentContainer
		}
		
		protected function createItemAttribute():void
		{
			_attribute = new ItemAttribute();
		}
		
	}
}